import Vue from 'vue'
import { getToken } from '@/utils/user'
import { adaptiveSelectFile } from './adaptive'
/**
 * 计算文件大小
 * @param {Number} fsize
 */
export function renderSize(fsize) {
  const unitArr = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']

  const srcsize = parseFloat(fsize)

  const index = Math.floor(Math.log(srcsize) / Math.log(1024))

  const size = (srcsize / Math.pow(1024, index)).toFixed(2)

  return size + unitArr[ index ]
}

/**
 * 上传文件至指定地址
 * @param {String} 服务器地址
 * @param {Object} 表单数据
 * @param {String} 文件路径
 */
export function uploadFile({ url, data, filePath }) {
  return new Promise((resolve, reject) => {
    Vue.prototype.$loading('上传中...')
    uni.uploadFile({
      url: `${ url }`,
      filePath,
      name: 'file',
      header: {
        'Authorization': getToken()
      },
      formData: data,
      success: (res) => {
        const data = JSON.parse(res.data)

        if (data.code === 200) {
          resolve(data)
        } else {
          reject(data.msg)
        }
      },
      fail: (err) => {
        console.log(err)
        reject('上传签名失败')
      },
      complete: () => {
        Vue.prototype.$hideLoading()
      }
    })
  })
}

/**
 * 上传文件到COS
 */
export function uploadCOS(filePath, signature, updateDom = null) {
  return new Promise((resolve, reject) => {
    const uploadTask = uni.uploadFile({
      url: `https://${ signature.bucketName }.cos.${ signature.region }.myqcloud.com/`,
      name: 'file',
      filePath,
      formData: {
        'key': signature.filename,
        'policy': signature.policy,
        'q-sign-algorithm': 'sha1',
        'q-ak': signature.secretId,
        'q-key-time': signature.keyTime,
        'q-signature': signature.signature
      },
      success: (res) => {
        if (res.statusCode === 204) {
          resolve(res)
        }
        reject(res)
      },
      fail: (err) => {
        reject(err)
      }
    })

    uploadTask.onProgressUpdate((res) => {
      if (updateDom) {
        updateDom(res.progress)
      }
    })
  })
}

/**
 * 选择文件
 * @param {Number} count 数量
 * @param {Number} maxSize 最大值，单位M
 */
export async function selectFile(count = 1, maxSize = 100) {
  const select = await Vue.prototype.$menuPicker(['图库中选择', '微信消息中选择'])

  let files = []

  try {
    Vue.prototype.$loading()
    switch (select) {
      case '图库中选择':
        const res = (await uni.chooseMedia({
          count,
          sourceType: ['album']
        }))

        if (res[ 1 ]) {
          files = res[ 1 ].tempFiles
        } else {
          throw new Error('选择文件错误')
        }
        break
      case '微信消息中选择':
        files = (await wx.chooseMessageFile({
          count,
        })).tempFiles
    }
    /* 适配输出 */
    files = files.map(file => adaptiveSelectFile(file))
    /* 大小过滤 */
    files = files.filter(file => {
      if (file.size > maxSize * 1024 * 1024) {
        Vue.prototype.$msg(`大于${ maxSize }M的文件将被过滤`)
        return false
      }
      return true
    })
  } catch (err) {
    console.log(err)
    return Promise.reject(err)
  }
  Vue.prototype.$hideLoading()
  return files
}
